package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.supplier.R;
import com.google.gson.Gson;

import java.math.BigDecimal;

/**
 * Created by wzh on 16-7-25.
 */
public class ProductPriceActivity extends AppActivity {


    private TextView tvPackageUnit;
    private TextView tvTitle;
    private EditText edPackage;

    private TextView tvMoq;
    private View vAdd;
    private View vReduce;

    //type == 1 库存,type==2起订量
    private int type;

    private String unit;
    private String value;
    private String productId;
    private Double incr = 1d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_product_rest);

        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("type", savedInstanceState.getInt("type", -1));
            getIntent().putExtra("incr", savedInstanceState.getInt("incr", 1));
            getIntent().putExtra("unit", savedInstanceState.getString("unit"));
            getIntent().putExtra("value", savedInstanceState.getString("value"));

        }
        incr = getIntent().getDoubleExtra("incr", 1f);
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        rightbtn.setText("保存");

        rightbtn.setVisibility(View.VISIBLE);

        tvPackageUnit = (TextView) findViewById(R.id.tv_package);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        edPackage = (EditText) findViewById(R.id.ed_package);
        tvMoq = (TextView) findViewById(R.id.tv_moq);
        vAdd = findViewById(R.id.iv_add);
        vReduce = findViewById(R.id.iv_remove);

        vAdd.setOnClickListener(this);
        vReduce.setOnClickListener(this);

        findViewById(R.id.tv_btn).setOnClickListener(this);
        type = getIntent().getIntExtra("type", -1);

        unit = getIntent().getStringExtra("unit");
        value = getIntent().getStringExtra("value");
        productId = getIntent().getStringExtra("productId");

        if (type == 1) {
            tvTitle.setText("库存");
            toolbarTitle.setText("库存");
            tvPackageUnit.setText(unit);
            tvMoq.setVisibility(View.GONE);
            vAdd.setVisibility(View.GONE);
            vReduce.setVisibility(View.GONE);
            CashierInputFilter filter = new CashierInputFilter();
            filter.MAX_VALUE = 99999999;
            edPackage.setFilters(new InputFilter[]{filter});
            edPackage.setText(value);
            edPackage.setSelection(edPackage.length());
        } else if (type == 2) {
            tvTitle.setText("起订量");
            toolbarTitle.setText("起订量");
            tvPackageUnit.setText(unit);
            edPackage.setVisibility(View.GONE);
            if (value == null || "".equals(value)) {
                tvMoq.setHint("0");
            }
            CashierInputFilter filter = new CashierInputFilter();
            filter.MAX_VALUE = 99999999;
            tvMoq.setFilters(new InputFilter[]{filter});
            tvMoq.setText(value);
        } else {
            finish();
        }


    }

    @Override
    public void onRightClick() {
        save();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.tv_btn:
                save();
                break;
            case R.id.iv_add:
                add(true);
                break;
            case R.id.iv_remove:
                add(false);
                break;

        }
    }

    private void add(boolean isAdd) {
        String s = tvMoq.getText().toString();
        if ("".equals(s)) {
            s = "0";
        }
        Double cnt = Double.valueOf(s);
        BigDecimal bdCnt = BigDecimal.valueOf(cnt);
        BigDecimal bdIncr = BigDecimal.valueOf(incr);
        BigDecimal add = null;
        if (isAdd) {
            add = bdCnt.add(bdIncr);

        } else {
            add = bdCnt.subtract(bdIncr);
        }

        if (add.compareTo(BigDecimal.ZERO) < 0) {
            add = BigDecimal.ZERO;
        }
        tvMoq.setText(FormatUtil.subZeroAndDot(add.toString()));
    }

    private void save() {

        String s = null;
        if (type == 1) {
            s = edPackage.getText().toString();
        } else {
            s = tvMoq.getText().toString();
        }

        if (TextUtils.isEmpty(s)) {
            if (type == 1) {
                toast("请输入库存");

            } else if (type == 2) {
                toast("请输入起订量");
            }
            return;
        }


        if (type == 2 && Float.valueOf(s) < 0.00000001) {
            toast("请输入合理的起订量");
            return;
        }


//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘

        if (productId != null && !"".equals(productId)) {

            if (type == 1) {
                requestProductModify(null, s);
            } else if (type == 2) {

                requestProductModify(s, null);
            }
        } else {

            Intent intent = new Intent();
            intent.putExtra("result", s);

            setResult(RESULT_OK, intent);

            finish();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("type", type);
        outState.putDouble("incr", incr);
        outState.putString("unit", unit);
        outState.putString("value", value);
        outState.putString("productId", productId);
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onToolbarBack() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        super.onToolbarBack();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void requestProductModify(String moq, String inventory) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify);
        RequestTag tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_product_modify;
        if (moq != null) {
            RequestEntityMapSupply.putParameter("moq", moq);
            tag.arg1 = moq;
        }
        if (inventory != null) {
            RequestEntityMapSupply.putParameter("inventory", inventory);
            tag.arg1 = inventory;
        }
        RequestEntityMapSupply.putParameter("id", productId);
        request(RequestEntityMapSupply, tag, onProductModifyRequestListener);

    }

    private OnRequestListener<StatusEntity> onProductModifyRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {

                if (tag != null && tag instanceof RequestTag) {
                    Intent intent = new Intent();

                    intent.putExtra("result", ((RequestTag) tag).arg1);

                    setResult(RESULT_OK, intent);
                }
                finish();
            } else {
                //没有数据
                toast("修改失败");

            }

        }
    };
}
